<?php
class XmlTools
{
    static public function print_r($simple_xml_node, $level = 0)
    {
        $tabs = str_repeat("\t", $level);
        $ret = "$tabs<" . $simple_xml_node->getName() . ">\n";
        $value = (string) $simple_xml_node;
        $ret .= !empty($value) ? $tabs . "\t" . $value . "\n" : "";
        foreach ($simple_xml_node as $one) {
            $ret .= self::print_r($one, $level + 1) . "\n";
        }
        $ret .= "$tabs</" . $simple_xml_node->getName() . ">";
        return $ret;
    }

    static public function array2attributesList($arr)
    {
        if (empty($arr)) return;
        if (!is_array($arr)) throw new Exception("not array");
        $ret = "";
        foreach ($arr as $key => $val) $pares[] = "$key=\"$val\"";
        return join(' ', $pares);
    }

    static public function array2xml($arr, $level = 0)
    {
        $tabs = str_repeat("\t", $level);
        $numeric_name = isset($arr["_numeric_tag"]) ? $arr["_numeric_tag"] : 'item';
        $ret = "";
        foreach ($arr as $key => $val) {
            //if(isset($arr["@$key"])) $attributes = " ".self::array2attributesList($arr["@$key"]);
            if ($key{0} == '_') continue; //служебный элемент не отображается
            $attributes = "";
            if (is_array($arr[$key]) && isset($arr[$key]['_attributes']))
                $attributes = " " . self::array2attributesList($arr[$key]['_attributes']);
            $element_name = $key;
            if (is_numeric($key))
                $element_name = $numeric_name;
            if (is_array($val) or $val instanceof Iterator) {
                $ret .= "$tabs<$element_name$attributes>\n";
                $ret .= self::array2xml($val, $level + 1);
                $ret .= "$tabs</$element_name>\n";
            }
            else {
                $ret .= "$tabs<$element_name$attributes>$val</$element_name>\n";
            }
        }
        return $ret;
    }

    static public function indent($xml)
    {
        $xml_no_spaces = preg_replace("/>\s+</s", "><", $xml);
        $r = new DOMDocument;
        $r->formatOutput = true;
        if (!@$r->loadHTML($xml_no_spaces)) return $xml; //если если XML не хороший, возвращаем его без изменений
        return $r->saveXML();
    }
}

?>